package com.shanghaionstar.discover.geofence.service;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.onstar.cn.api.UsersService;
import com.onstar.cn.auth.userProfile.Vehicle;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.framework.annotation.http.HeadsValue;
import com.onstar.cn.framework.annotation.http.Request;
import com.onstar.cn.framework.mvp.base.core.BaseService;
import com.onstar.cn.framework.network.HttpInjectUtils;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.network.enumtype.HttpAccept;
import com.onstar.cn.framework.network.enumtype.HttpMethod;
import com.onstar.cn.framework.network.enumtype.Language;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.mag.GeoFencingDTO;
import com.onstar.cn.mag.GeofenceInfoEntity;
import com.onstar.cn.mag.poi.Coordinate;
import com.onstar.cn.more.response.PersonalInfoResponse;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.AlertType;
import com.shanghaionstar.user.service.AccountInfoService;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.NetConnectUtil;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;

import rx.Observable;
import rx.functions.Func0;

/**
 * Created by 7828wc on 16/7/21.
 */
public class GeofenceService extends BaseService<GeofenceInfoEntity> {
    private Context context;

    public GeofenceService(Context context) {
        this.context = context;
    }

    @Override
    public RequestEntity getRequestEntity() {
        return null;
    }

    @Override
    public GeofenceInfoEntity jsonToBean(String json) {
        return null;
    }

    public Observable<String> init() {
        return Observable.defer(new Func0<Observable<String>>() {
            @Override
            public Observable<String> call() {
                return Observable.just("init");
            }
        });
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.GET)
    public Observable<List<GeofenceInfoEntity>> getGeofencing() {
        return Observable.defer(new Func0<Observable<List<GeofenceInfoEntity>>>() {
            @Override
            public Observable<List<GeofenceInfoEntity>> call() {
                try {
                    UsersService joinmeService = new UsersService(Constants.CURRENT_SERVER_URL);
                    RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
                    requestEntity = joinmeService.getGeoFencings(requestEntity, ApplicationUtil.getInstance().getSubscriberID(), ApplicationUtil.getInstance().getAccountId(), ApplicationUtil.getInstance().getVin());

                    requestEntity = HttpInjectUtils.injectHttp(GeofenceService.this.getClass(), "getGeofencing", requestEntity);

                    return Observable.just((List<GeofenceInfoEntity>) new Gson().fromJson(BusinessUtil.getResponse(getDatas(requestEntity), context),new TypeToken<ArrayList<GeofenceInfoEntity>>(){}.getType()));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.PUT)
    public Observable<String> processGeofencing(final GeofenceInfoEntity geofenceInfoEntity) {
        return Observable.defer(new Func0<Observable<String>>() {
            @Override
            public Observable<String> call() {
                try {
                    UsersService joinmeService = new UsersService(Constants.CURRENT_SERVER_URL);
                    RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
                    LinkedHashMap<String, Object> coHashMap = new LinkedHashMap<String, Object>();
                    coHashMap.put(FinalConstants.HTTP_AUTHORIZATION, ApplicationUtil.getInstance().getToken());
                    requestEntity.setCustomHeads(coHashMap);
                    requestEntity = joinmeService.processGeoFencing( requestEntity, ApplicationUtil.getInstance().getSubscriberID(),
                            ApplicationUtil.getInstance().getAccountId(), ApplicationUtil.getInstance().getVin());
//                    requestEntity = joinmeService.getGeoFencings(requestEntity, ApplicationUtil.getInstance().getSubscriberID(), ApplicationUtil.getInstance().getAccountId(), ApplicationUtil.getInstance().getVin();

                    GeoFencingDTO dto = createGeoFencingDTO(geofenceInfoEntity);
                    requestEntity.setBody(new Gson().toJson(dto));
                    requestEntity = HttpInjectUtils.injectHttp(GeofenceService.this.getClass(), "processGeofencing", requestEntity, GeofenceInfoEntity.class);

                    return Observable.just(BusinessUtil.getResponse(getDatas(requestEntity), context));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    public GeoFencingDTO createGeoFencingDTO(GeofenceInfoEntity geoFenceInfo) {
        GeoFencingDTO fencingDTO = new GeoFencingDTO();
        fencingDTO.setGeoFencingID(geoFenceInfo.getGeoFencingID());
        Vehicle vehicle =ApplicationUtil.getInstance().getCurrentVehicle();
        fencingDTO.setVin(vehicle==null?"":vehicle.getVin());
        // fencingDTO.setAcctNum(((MyApp) context).getCurrent_accountno());
        Coordinate centerPoiCoordinate = new Coordinate();
        if(!CommonUtil.isNull(geoFenceInfo.getCenterPoiCoordinate().getLatitude())) {
            centerPoiCoordinate.setLatitude(Double.valueOf(geoFenceInfo.getCenterPoiCoordinate().getLatitude()));
        }
        if(!CommonUtil.isNull(geoFenceInfo.getCenterPoiCoordinate().getLongitude())) {
            centerPoiCoordinate.setLongitude(Double.valueOf(geoFenceInfo.getCenterPoiCoordinate().getLongitude()));
        }
        fencingDTO.setCenterPoiCoordinate(geoFenceInfo.getCenterPoiCoordinate());
        fencingDTO.setCenterPoiName(geoFenceInfo.getCenterPoiName());
        fencingDTO.setGeoFencingName(geoFenceInfo.getGeoFencingName());
        fencingDTO.setOperationType(geoFenceInfo.getOperationType());
        fencingDTO.setCenterPoiAddress(geoFenceInfo.getCenterPoiAddress());
        String range = geoFenceInfo.getRange();
        if (range.toLowerCase(Locale.CHINA)
                .contains(context.getString(R.string.geofence_range_unit_km).toLowerCase(Locale.CHINA))) {
            range = range.toLowerCase(Locale.CHINA)
                    .replace(context.getString(R.string.geofence_range_unit_km).toLowerCase(Locale.CHINA), "");
        }
        if (range.toLowerCase(Locale.CHINA)
                .contains(context.getString(R.string.geofence_range_unit_m).toLowerCase(Locale.CHINA))) {
            range = range.toLowerCase(Locale.CHINA)
                    .replace(context.getString(R.string.geofence_range_unit_m).toLowerCase(Locale.CHINA), "");
        }
        fencingDTO.setRange(range);
        fencingDTO.setAlertType(geoFenceInfo.getAlertType());
        if (!CommonUtil.isNull(geoFenceInfo.getRule())) {
            if (geoFenceInfo.getRule().equals(context.getString(R.string.out_geofence))) {
                fencingDTO.setAlertType(AlertType.Out.value());
            } else {
                fencingDTO.setAlertType(AlertType.In.value());
            }
        } else {
            fencingDTO.setAlertType(AlertType.All.value());
        }
//        fencingDTO.setRangeUnit(geoFenceInfo.getRangeUnit());
        if (geoFenceInfo.getRangeUnit().toLowerCase(Locale.CHINA).equals("KM")) {
            fencingDTO.setRangeUnit(geoFenceInfo.getRangeUnit().toLowerCase(Locale.CHINA));
        } else if (geoFenceInfo.getRangeUnit().toLowerCase(Locale.CHINA).equals("M")) {
            fencingDTO.setRangeUnit(geoFenceInfo.getRangeUnit().toLowerCase(Locale.CHINA));
        } else {
            if (geoFenceInfo.getRangeUnit().equals("千米")) {
                fencingDTO.setRangeUnit("KM");
            } else if (geoFenceInfo.getRangeUnit().equals("米")) {
                fencingDTO.setRangeUnit("M");
            }
        }
        fencingDTO.setVehMake(ApplicationUtil.getInstance().getCurrentVehicle().getMake());
        fencingDTO.setVehModel(ApplicationUtil.getInstance().getCurrentVehicle().getModel());
        fencingDTO.setMobilePhone(geoFenceInfo.getMobilePhone());
        fencingDTO.setGeoFencingStatus(geoFenceInfo.getGeoFencingStatus());
        if (geoFenceInfo.getOperationType().equals(Constants.OPERATE_TYPE_UPDATE)) {
            fencingDTO.setExpiredDate(geoFenceInfo.getExpiredDate());
        } else {
            fencingDTO.setExpiredDate("");
        }
        return fencingDTO;
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.GET)
    public Observable<PersonalInfoResponse> getOwnerMobilePhone() {
        return Observable.defer(new Func0<Observable<PersonalInfoResponse>>() {
            @Override
            public Observable<PersonalInfoResponse> call() {
                try {
                    RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);

                    AccountInfoService service = new AccountInfoService(context);
                    requestEntity = service.getRequestEntity();
                    requestEntity = HttpInjectUtils.injectHttp(GeofenceService.this.getClass(), "getOwnerMobilePhone", requestEntity);

                    return Observable.just(GsonHelper.fromJson(BusinessUtil.getResponse(getDatas(requestEntity), context),PersonalInfoResponse.class));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }


}
